import React, { useState, useEffect } from 'react'
import './Administration.css'
import { useNavigate } from 'react-router-dom'
import { Input, Select, Radio, RadioChangeEvent, Image, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getGoodsTypeList, getGoodsBrandList, getGoodsTagList, addGoods } from '../../../request/api'
import { useDispatch, useSelector } from 'react-redux';
import { setIsGoods } from '../../../store/module/store';

export default function Add_goods() {

    const navigate = useNavigate()
    const dispatch = useDispatch()
    //上传图片

    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

    const getBase64 = (file: FileType): Promise<string> => //将图片转为base64
        new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file); //将图片转为base64
            reader.onload = () => resolve(reader.result as string); //如果转换成功，则返回base64
            reader.onerror = (error) => reject(error); //如果转换失败，则抛出错误
        });
    const [previewOpen, setPreviewOpen] = useState(false); //预览图片
    const [previewImage, setPreviewImage] = useState(''); //预览图片
    const [fileList, setFileList] = useState<UploadFile[]>([]); //图片列表
    //上传图片
    const handlePreview = async (file: UploadFile) => { //预览        
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as FileType); //获取图片
        }
        setPreviewImage(file.url || (file.preview as string)); //设置图片预览
        setPreviewOpen(true); //设置图片预览
    };

    const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) => {//上传图片
        setFileList(newFileList); //设置图片
    }

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>点击上传</div>
        </button>
    );

    //取消添加
    const cancel = () => {
        setFileList([]); //清空图片
        navigate('/home/Commodity/CommodityAdministration'); //跳转
    }

    useEffect(() => {
        getTypeList(); //获取商品类型
        getBrandList(); //获取商品品牌
        getTagList(); //获取商品标签
    }, [])

    //获取到商品类型
    const [typeList, setTypeList] = useState([]); //商品类型
    const getTypeList = async () => {
        let res = await getGoodsTypeList({})
        setTypeList(res.list)
    }
    //获取到商品品牌
    const [brandList, setBrandList] = useState([]); //商品品牌
    const getBrandList = async () => {
        let res = await getGoodsBrandList({})
        setBrandList(res.list)
    }
    //获取到商品标签
    const [tagList, setTagList] = useState([]); //商品标签
    const getTagList = async () => {
        let res = await getGoodsTagList({})
        setTagList(res.list)
    }

    const [name, setName] = useState('') //商品名称
    const [description, setDescription] = useState('') //商品描述
    const [price, setPrice] = useState() //价格
    const [discount, setDiscount] = useState() //折扣
    const [type, setType] = useState('') //商品类型
    const [limited, setLimited] = useState() //限购数量
    const [sell, setSell] = useState(0) //已售数量
    const [shopid, setShopid] = useState('') //商品编号
    const [brand, setBrand] = useState('') //品牌
    const [specification, setSpecification] = useState('') //规格
    const [Production, setProduction] = useState('') //生产日期
    const [shelflife, setShelflife] = useState('') //保质期
    const [storagemode, setStoragemode] = useState('') //储存方式
    const [inventory, setInventory] = useState() //库存
    const [label, setLabel] = useState('') //标签
    const [statue, setStatue] = useState<string>('启用') //状态

    //下拉选择事件 类型
    const handleChange_statue = (value: string) => { //状态
        setType(value)
    };
    //下拉选择事件 标签
    const handleChange_tag = (value: string) => { //状态
        setLabel(value)
    };
    //下拉选择事件 品牌
    const handleChange_brand = (value: string) => { //状态
        setBrand(value)
    };


    //单选框
    const [value, setValue] = useState(0); //单选框
    const onChange = (e: RadioChangeEvent) => {
        setValue(e.target.value.img);
    };

    //添加商品
    const add_goods = async () => {
        if (!name && !description && !price && !discount && !type && !fileList && !detailsimg) {
            return alert('请输入完整信息')
        } else {
            let img = fileList[0].response.img
            let imga: any = []
            if (!imga) {
                fileList.map((item) => {
                    imga.push(item.response.img)
                })
            } else {
                imga = []
                fileList.map((item) => {
                    imga.push(item.response.img)
                })
            }

            let data = {
                name: name, //名称
                description: description, //描述
                price: price, //价格
                discount: discount, //折扣
                type: type, //类型
                img: img, //图片
                detailsimg: imga, //详情图片
                limited: limited, //限购
                sell: sell, //销量
                shopid: shopid, //店铺id
                brand: brand, //品牌
                specification: specification, //规格
                Production: Production, //生产日期
                shelflife: shelflife, //保质期
                storagemode: storagemode, //存储方式
                inventory: inventory, //库存
                label: label, //标签
                status: value, //状态
            }
            let res = await addGoods({data})
            if (res.code === 200) {
                alert('添加成功')
                setFileList([]); //清空图片
                dispatch(setIsGoods())
                navigate('/home/Commodity/CommodityAdministration'); //跳转
            }
        }
    }
    return (
        <div className='Add_goods'>
            <p style={{
                backgroundColor: '#f0f0f0',
                fontSize: '0.35rem',
                padding: '0.15rem 0.2rem',
                display: 'flex',
                justifyContent: 'space-between',
            }}>
                <span>商品基础信息</span>
                <span>
                    <button style={{ padding: '0.15rem 0.3rem', margin: '0.1rem' }}
                        onClick={() => {
                            cancel();
                        }}
                    >取消</button>
                    <button style={{ padding: '0.15rem 0.3rem', margin: '0.1rem', border: '1px solid red', color: 'red' }}
                        onClick={() => {
                            add_goods();
                        }}>创建</button>
                </span>
            </p>
            <div>
                <p><span>*商品编号</span><input type="text" placeholder='请输入商品编号' value={shopid} onChange={(e) => setShopid(e.target.value)} /></p>
                <p><span>*商品名称</span><input type="text" placeholder='请输入商品名称' value={name} onChange={(e) => setName(e.target.value)} /></p>
                <p><span>*商品描述</span><input type="text" style={{ width: '13rem' }} placeholder='请输入商品描述' value={description} onChange={(e) => setDescription(e.target.value)} /></p>
                <div style={{ margin: '0.35rem', width: '5.5rem', borderRadius: '0', fontSize: '0.22rem' }}>
                    <span style={{ marginLeft: '0.13rem' }}>商品分类：</span>
                    <Select
                        defaultValue="全部"
                        style={{ width: '4rem', borderRadius: '0', fontSize: '0.22rem' }}
                        onChange={handleChange_statue}
                        options={typeList.map(item => {
                            return { value: item._id, label: item.type }
                        })}
                    />
                </div>
                <div style={{ margin: '0.35rem', width: '5.5rem', borderRadius: '0', fontSize: '0.22rem' }}>
                    <span style={{ marginLeft: '0.13rem' }}>商品标签：</span>
                    <Select
                        defaultValue="全部"
                        style={{ width: '4rem', borderRadius: '0', fontSize: '0.22rem' }}
                        onChange={handleChange_tag}
                        options={tagList.map(item => {
                            return { value: item.name, label: item.name }
                        })}
                    />
                </div>
                <div style={{ margin: '0.35rem', width: '5.5rem', borderRadius: '0', fontSize: '0.22rem' }}>
                    <span style={{ marginLeft: '0.13rem' }}>商品品牌：</span>
                    <Select
                        defaultValue="全部"
                        style={{ width: '4rem', borderRadius: '0', fontSize: '0.22rem' }}
                        onChange={handleChange_brand}
                        options={brandList.map(item => {
                            return { value: item.name, label: item.name }
                        })}
                    />
                </div>

                <p><span>商品规格</span><input type="text" placeholder='请输入商品规格' value={specification} onChange={e => setSpecification(e.target.value)} /></p>
                <p><span>*生产日期</span><input type="date" placeholder='请输入生产日期' value={Production} onChange={e => setProduction(e.target.value)} /></p>
                <p><span>*保质期限</span><input type="text" placeholder='请输入保质期限' value={shelflife} onChange={e => setShelflife(e.target.value)} /></p>
                <p><span>存储方式</span><input type="text" placeholder='请输入存储方式' value={storagemode} onChange={e => setStoragemode(e.target.value)} /></p>
                <p><span>*商品状态</span>
                    <button style={{
                        padding: '0.1rem 0.25rem',
                        margin: '0.1rem',
                        backgroundColor: 'white',
                        border: statue === '启用' ? '1px solid red' : '1px solid black',
                        color: statue === '启用' ? 'red' : 'black'
                    }}
                        onClick={() => {
                            setStatue('启用')
                        }}
                    >启用</button>
                    <button style={{
                        padding: '0.1rem 0.25rem',
                        margin: '0.1rem',
                        backgroundColor: 'white',
                        border: statue !== '启用' ? '1px solid red' : '1px solid black',
                        color: statue !== '启用' ? 'red' : 'black'
                    }}
                        onClick={() => {
                            setStatue('禁用')
                        }}
                    >禁用</button>
                </p>
            </div>
            <p style={{
                backgroundColor: '#f0f0f0',
                fontSize: '0.35rem',
                padding: '0.15rem 0.2rem',
            }}>商品价格信息</p>
            <div>
                <p><span>*库存数量</span><input type="number" placeholder='请输入库存数量' value={inventory} onChange={(e) => setInventory(e.target.value)} />个</p>
                <p><span>*销售价格</span><input type="number" placeholder='请输入销售价格' value={price} onChange={(e) => setPrice(e.target.value)} />元</p>
                <p><span>*商品折扣</span><input type="number" placeholder='商品折扣如0.80' value={discount} onChange={(e) => setDiscount(e.target.value)} />折</p>
                <div style={{ padding: '0.1rem 0.3rem' }}>
                    <span style={{
                        marginRight: '0.25rem',
                    }}>是否限购</span>
                    <Radio.Group onChange={onChange} value={value} defaultValue={'不限购'}>
                        <Radio value={0}><span >不限购</span></Radio>
                        <Radio value={10}><span >*限购</span> </Radio>
                    </Radio.Group>
                    <input type="number" style={{ display: value !== 0 ? 'inline-block' : 'none' }} placeholder='请输入限购数量'
                        value={limited} onChange={(e) => setLimited(e.target.value)}
                    />
                </div>
            </div>
            <p style={{
                backgroundColor: '#f0f0f0',
                fontSize: '0.35rem',
                padding: '0.15rem 0.2rem',
            }}>商品主视图(最多添加五张)</p>
            <div>
                <span style={{
                    marginLeft: '0.4rem',
                    marginTop: '0.2rem',
                }}>第一张照片为展示图</span>
            </div>
            <div style={{
                padding: '0.1rem 0.3rem',
            }}>
                <Upload
                    action="http://localhost:3000/commodity/index/upload"
                    listType="picture-card" // 设置上传列表的内建样式，支持 picture 和 text 两种基本样式
                    fileList={fileList} // 上传列表中已上传的文件
                    onPreview={handlePreview} // 点击文件链接或预览图标时的回调
                    onChange={handleChange} // 上传文件改变时的回调
                >
                    {fileList.length >= 5 ? null : uploadButton}
                </Upload>
                {previewImage && (
                    <Image
                        wrapperStyle={{ display: 'none' }}
                        preview={{
                            visible: previewOpen,
                            onVisibleChange: (visible) => setPreviewOpen(visible),
                            afterOpenChange: (visible) => !visible && setPreviewImage(''),
                        }}
                        src={previewImage}
                    />
                )}
            </div>

        </div>
    )
}
